package com.javen.study.handler;

import com.javen.study.enums.CommonEnums;
import com.javen.study.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.*;

/**
 * @Author: tujw@netinnet.cn
 * @Date: 2022/11/18 16:04
 * @Description: 统一异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 对方法参数校验异常处理方法
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ResultVO> handlerNotValidException(MethodArgumentNotValidException exception) {
        log.info("统一处理异常：MethodArgumentNotValidException");
        BindingResult result = exception.getBindingResult();
        Map<String, Object> maps;

        if (result.hasErrors()) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            maps = new HashMap<>(fieldErrors.size());
            fieldErrors.forEach(error -> {
                maps.put(error.getField() + "：" + error.getRejectedValue(), error.getDefaultMessage());
            });
        } else {
            maps = Collections.EMPTY_MAP;
        }
        //响应对象ResponseEntity可指定http响应码
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ResultVO.error(CommonEnums.ResultEnum.PARAM_VALID_ERROR, maps));
    }

    /**
     * 异常处理方法
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ResultVO> handlerException(Exception exception) {
        log.info("统一处理异常：{}", exception.getClass());
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ResultVO.customerError(exception.getMessage(), null));
    }

    /**
     * 空指针异常处理方法
     */
    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity<ResultVO> handlerNullPointerException(Exception exception) {
        log.info("统一处理异常：{}", exception.getClass());
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ResultVO.customerError(exception.getMessage(), null));
    }

    public static void main(String[] args) {
        Integer a = 1111;
        Long b = 1111L;
        System.out.println(a.equals(b));
    }

}
